<template>
	<view class="input-code-item" v-else>
		<view class="input-item">
			<text>验证码</text>
			<input placeholder-class="place" v-model="code" type="text" placeholder="请输入验证码">
		</view>
		<button size="mini" :disabled="isCaptcha" @click="earnCaptcha">{{!isCaptcha?'获取验证码':`已发送(${time})`}}</button>
	</view>
</template>

<script>
	import { getCaptcha, checkCaptcha } from '../../api/index.js'
	// 定时器返回值
	let timer = 0
	export default {
		data() {
			return {
				isCaptcha: false,
				// 验证码
				code: '',
				time: 30
			}
		},
		props: ['tel', 'clickLoginBtn'],
		watch: {
			clickLoginBtn(newVal) {
				if (newVal) this.setCode()
			}
		},
		methods: {
			// 检查验证码
			checkCode() {
				return checkCaptcha({phone: this.tel, captcha: this.code})
			},
			// 获取验证码
			async earnCaptcha() {
				if (getApp().checkPhone(this.tel)) {
					this.handleCountDown()
					await getCaptcha({phone: this.tel})
					uni.showToast({
						title: '短信已发,请查收!'
					})
				}
			},
			// 失去焦点触发
			async setCode() {
				let res = await this.checkCode()
				// 向父组件传值
				this.$emit('getCode', { code: this.code, codeDetail: res?.data, clickLoginBtn: false })
			},
			 // 倒计时
			handleCountDown() {
				this.isCaptcha = true
				timer = setInterval(() => {
					this.time--
					if (this.time === 0) {
						clearInterval(timer)
						this.time = 30
						this.isCaptcha = false
					}
				}, 1000)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.input-code-item {
		display: flex;

		button {
			height: 130rpx;
			line-height: 130rpx;
			color: $uni-color-theme;
			margin: 0;
		}
	}
</style>
